package com.gxa.insurance.controller;

import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.util.JsonResult;
import com.gxa.insurance.util.StringUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileFilter;
import java.security.PublicKey;
import java.util.Map;

/**
 * @author Min
 */
@RestController
@ApiOperation("删除文件操作")
@RequestMapping("/delete")
@CrossOrigin
public class DeleteFileController {
    @GetMapping("/file")
    @ApiImplicitParam(name = "fileName",value = "例：2c45bece188f4e35869d00cb990eeee8.png")
    public Map deleteFile(@RequestParam("fileName")String fileName, @ApiIgnore HttpServletRequest request) throws BusinessException {
        if(StringUtil.isEmpty(fileName)){
            throw new BusinessException(ExceptionCode.WRONG_VALUE);
        }
        // 获取当先应用根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        File file = new File(realPath);
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                System.out.println(pathname.getName());
                if(pathname.getName().equals(fileName)){
                    return true;
                }
                return false;
            }
        });

        // 删除文件
        for (File findFile : files) {
            findFile.delete();
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("删除成功");
        return jsonResult.getMap();
    }

}
